package com.guodi.map.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.PageData;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.core.minio.util.MinioUtil;
import com.guodi.core.secure.LoginUser;
import com.guodi.core.tool.api.R;
import com.guodi.core.tool.utils.Func;
import com.guodi.map.entity.MapLayer;
import com.guodi.map.entity.MapLayerCollect;
import com.guodi.map.entity.MapProjectDir;
import com.guodi.map.entity.MapProjectFile;
import com.guodi.map.service.*;
import com.guodi.map.utils.RecursionUtil;
import com.guodi.map.utils.VerificationUtil;
import com.guodi.map.vo.ApiMapProjectDir;
import com.guodi.system.feign.IDictClient;
import com.guodi.system.vo.DictVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @描述：专题目录/图层控制类
 * @作者: 代鹏刚
 * @日期: 2019-12-11
 */
@Validated
@RestController
@RequestMapping("/MapProjectDir")
@Api(value = "API - MapProjectDirController", tags = "专题目录图层")
public class MapProjectDirController extends BaseController {

    @Autowired
    private IMapProjectDirService mapProjectDirService;
    @Autowired
    private IMapLayerService mapLayerService;
    @Autowired
    private IMapProjectAuthService mapProjectAuthService;
    @Resource
    private IDictClient iDictBizClient;
    @Autowired
    private IMapProjectFileService mapProjectFileService;
    @Autowired
    private IMapCommonService commonService;
    @Autowired
    private IMapLayerCollectService iMapLayerCollectService;
    @Resource
    private IMapProjectDirService iMapProjectDirService;

    /**
    * @描述: 根据专题id、用户id查询专题授权图层树
    * @作者: 代鹏刚
    * @日期: 2019/12/11 10:42
    **/
    @PostMapping("/listTreeByProjectIdAndUserId")
    @ApiOperation(value = " 根据专题id、用户id查询专题授权图层树")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "专题id", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "目录/图层名称", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isDir", value = "是否为目录层(true:是 false:否)", required = true, dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "所属机构ID", required = false, dataType = "string", paramType = "query")
    })
    public R<List<MapProjectDir>> listTreeByProjectIdAndUserId(@ApiIgnore MapProjectDir mapProjectDir) {
        // 根据上级目录id、用户id查询专题授权图层
        List<MapProjectDir> dataList = mapProjectDirService.listTreeByProjectIdAndUserId(mapProjectDir);
        //2020-0508兼容pgSQL
        boolean isTrue = dataList.stream().filter(m -> m.getTreeLevel() == 0).findAny().isPresent();
        if(isTrue){
            List<MapProjectDir> resultList = new ArrayList<>();
            sortList(dataList,"-1",resultList);
            return R.data(resultList);
        }else {
            return R.data(dataList);
        }
    }
    /**
     * @作者: 林楷 2021/5/25
     * @描述: 根据专题id、父级ID查询专题授权图层列表
     * @参数: null
     * @返回: null
     */
    @PostMapping("/listTreeByProjectIdAndUserIdLazyLoad")
    @ApiOperation(value = "根据专题id、父级ID查询专题授权图层列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "专题id", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "目录/图层名称", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isDir", value = "是否为目录层(true:是 false:否)", required = true, dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "所属机构ID", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "上级目录ID", required = true, dataType = "string", paramType = "query")
    })
    public R<List<MapProjectDir>> listTreeByProjectIdAndUserIdLazyLoad(@ApiIgnore MapProjectDir mapProjectDir) {
        // 根据上级目录id、用户id查询专题授权图层
        List<MapProjectDir> dataList = mapProjectDirService.listTreeByProjectIdAndUserIdLazyLoad(mapProjectDir);
        return R.data(dataList);
    }

    public static void sortList(List<MapProjectDir> list, String id, List<MapProjectDir> resultList) {
        for (MapProjectDir node :list) {
            if (node.getParentId().equals(id)) {
                node.setTreeLevel(node.getTreeLevel()+1);
                resultList.add(node);
                sortList(list,node.getId(),resultList);
            }
        }
    }

    /**
    * @描述: 根据实体属性分页查询
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2019-12-11
    **/
    @PostMapping("/listByEntity")
    @ApiOperation(value = " 根据实体属性分页查询")
    public R listByEntity(Page page, MapProjectDir mapProjectDir){
        LambdaQueryWrapper<MapProjectDir> wrapper = new QueryWrapper().lambda();
        IPage<MapProjectDir> iPage = mapProjectDirService.page(page, wrapper);
        return R.data(iPage);
    }

    /**
     * @描述: 根据主键查询
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-11
     **/
    @PostMapping("/findById")
    @ApiOperation(value = "根据主键查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true,
                    dataType = "string", paramType = "query")
    })
    public R findById(String id) {
        if(StringUtils.isBlank(id)){
            return R.fail(StatusCode.ERROR_CODE_40005,"id不能为空");
        }
        MapProjectDir mapProjectDir = mapProjectDirService.getById(id);
        return R.data(mapProjectDir);
    }

    /**
    * @描述: 根据专题集code查询
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020/3/11 10:34
    **/
    @PostMapping("/findByCode")
    @ApiOperation(value = "根据专题集code查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "专题集编码", required = true, dataType = "string", paramType = "query")
    })
    public R findByCode(String code) {
        List<MapProjectDir> mapProjectDir = mapProjectDirService.findByCode(code);
        return R.data(mapProjectDir);
    }

    /**
     * @描述: 新增
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-11
     **/
    @PostMapping("/save")
    @ApiOperation(value = "新增")
    public R save(@Valid ApiMapProjectDir apiMapProjectDir){
        MapProjectDir mapProjectDir = new MapProjectDir();
        BeanUtils.copyProperties(apiMapProjectDir,mapProjectDir);
        if(!prepareData(mapProjectDir, true)){
            return R.fail(StatusCode.ERROR_CODE_40005,"该专题名称已经存在，请更换！");
        }
        Integer sort = commonService.getMaxSort(mapProjectDir.getParentId(), "map_project_dir");
        mapProjectDir.setId(UuidUtil.get32UUID());
        mapProjectDir.setSort(sort + 1);
        //图层新增别名-0325
        if(mapProjectDir.getType() != 1){
            mapProjectDir.setAlias(mapProjectDir.getName());
        }
        mapProjectDirService.save(mapProjectDir);
        return R.data(mapProjectDir);
    }

    /**
     * @描述: 修改
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-11
     **/
    @PostMapping("/update")
    @ApiOperation(value = "修改")
    public R update(MapProjectDir mapProjectDir) {
        if(StringUtils.isBlank(mapProjectDir.getId())){
            return R.fail(StatusCode.ERROR_CODE_40005,"数据Id不能为空");
        }
        //20200327新增别名唯一验证
        if(!prepareData(mapProjectDir, false)){
            return R.fail(StatusCode.ERROR_CODE_40005,"该专题别名已经存在，请更换！");
        }
        mapProjectDirService.updateById(mapProjectDir);
        // 获取图层信息
        MapProjectDir projectDir = mapProjectDirService.getById(mapProjectDir.getId());
        MapLayer mapLayer = mapLayerService.getById(projectDir.getLayerId());
        projectDir.setMapLayer(mapLayer);
        return R.data(projectDir);
    }

    /**
     * @描述: 根据主键批量删除
     * @入参: ids
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-11
     **/
    @PostMapping("/delete")
    @ApiOperation(value = "根据主键批量删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "批量删除", required = true, allowMultiple=true,dataType = "string", paramType = "query")
    })
    @Transactional(rollbackFor = Exception.class)
    public R delete(String[] ids){
        //删除地图专题授权的数据
        mapProjectAuthService.deleteByIds(ids);
        //删除表数据
        mapProjectDirService.deleteByIds(ids);
        //删除对应的附件
        List<MapProjectFile> mapProjectFiles = mapProjectFileService.getAllChildrenById(Arrays.asList(ids), null);
        // 删除FDFS附件信息
        if(mapProjectFiles.size() > 0){
            for (MapProjectFile mapProjectFile:mapProjectFiles) {
                if(mapProjectFile.getType() == 2 && StringUtils.isNotBlank(mapProjectFile.getFilePath())){
                    MinioUtil.removeFile(mapProjectFile.getFilePath());
                }
            }
            //删除表数据
            List<String> idList = mapProjectFiles.stream().map(x->x.getId()).collect(Collectors.toList());
            mapProjectFileService.deleteByIds(idList);
        }
        return R.data(null);
    }

    /**
    * @描述: 懒加载关联图层
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020/1/10 11:18
    **/
    @PostMapping("/lazyLoadMapLayer")
    @ApiOperation(value = "懒加载关联图层")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dirId", value = "当前选中的专题目录ID", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "关联图层的父级ID",  required = true, dataType = "string", paramType = "query")
    })
    public R lazyLoadMapLayer(String dirId, String parentId){
        List<MapLayer> list = mapLayerService.lazyLoadMapLayer(dirId,parentId);
        list = mapLayerService.getServiceAndLayer(list);
        List<MapLayer> mapLayers = RecursionUtil.buildLayerTree(list);
        return R.data(mapLayers);
    }

    /**
     * @描述: 懒加载行政区划关联图层
     * @入参:
     * @出参:
     * @作者: 郑文彬
     * @日期: 2020/1/10 11:18
     **/
    @PostMapping("/lazyLoadDivisionMapLayer")
    @ApiOperation(value = "懒加载行政区划关联图层")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "父id", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isFilter", value = "是否过滤行政区域路径中关联的图层", dataType = "boolean", paramType = "query")
    })
    public R lazyLoadDivisionMapLayer(String parentId, boolean isFilter){
        String[] parentIdSplit = parentId.split(",");
        List<MapLayer> treeList = new LinkedList<>();
        for(String pid : parentIdSplit) {
            List<MapLayer> list = mapLayerService.lazyLoadDivisionMapLayer(pid,isFilter);
            Optional<MapLayer> root = list.stream().filter(dir -> dir.getId().equals(pid)).findAny();
            if (root.isPresent()){
                treeList.addAll(RecursionUtil.buildLayerTree(list,root.get().getParentId()));
            }else{
                treeList.addAll(RecursionUtil.buildLayerTree(list));
            }
        }
        return R.data(treeList);
    }


    /**
    * @描述: 保存关联图层
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2019/12/16 11:18
    **/
    @PostMapping("/saveLinkLayer")
    @ApiOperation("保存关联图层")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectId", value = "专题id", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "names", value = "图层名称", required = true,allowMultiple=true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "上级目录ID", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "所属机构ID", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "LinkLayers", value = "图层Id数组", required = true, allowMultiple=true,dataType = "string", paramType = "query")
    })
    public R saveLinkLayer(String projectId, String[] names, String parentId, String orgId, String[] LinkLayers){
        //验证当前目录下是否存在重名
        List<MapProjectDir> list = mapProjectDirService.verifyByNames(names,parentId);
        if(list.size() > 0){
            return R.fail(StatusCode.ERROR_CODE_40005,"该目录下已存在名称为"+list.get(0).getName()+"的空图层，请更换！");
        }
        //查询当前目录下包含了多少图层
        Integer sort = commonService.getMaxSort(parentId, "map_project_dir");
        //定义存储数据的集合
        List<MapProjectDir> mapProjectDirList = new ArrayList<>();
        List<String> layerIdList = Arrays.asList(LinkLayers);
        List<MapLayer> mapLayers = mapLayerService.listByIds(layerIdList);
        Map<String, MapLayer> collect = mapLayers.stream().collect(Collectors.toMap(MapLayer::getId, vo -> vo));
        for(int i = 0; i < names.length; i++){
            sort++;
            MapProjectDir mapProjectDir = new MapProjectDir();
            mapProjectDir.setId(UuidUtil.get32UUID());
            mapProjectDir.setLayerId(LinkLayers[i]);
            mapProjectDir.setName(collect.get(LinkLayers[i]).getName());
            mapProjectDir.setType(2);
            mapProjectDir.setIsShow(0);
            mapProjectDir.setIsEdit(1);
            mapProjectDir.setProjectId(projectId);
            mapProjectDir.setParentId(parentId.trim());
            mapProjectDir.setOrgId(orgId);
            mapProjectDir.setCreator(getUser().getUserId().toString());
            mapProjectDir.setCreateTime(new Date());
            //防止误修改
            mapProjectDir.setModifier(null);
            mapProjectDir.setModifyTime(null);
            mapProjectDir.setSort(sort);
            //新增别名-0325
            mapProjectDir.setAlias(names[i]);
            // 设置默认值
            mapProjectDir.setIsCommon(0);
            mapProjectDir.setIsCollect(0);
            mapProjectDir.setIsLayerDir(0);
            // 拼接图层信息
            MapLayer mapLayer = mapLayerService.getById(mapProjectDir.getLayerId());
            mapProjectDir.setMapLayer(mapLayer);
            mapProjectDirList.add(mapProjectDir);
        }
        mapProjectDirService.saveBatch(mapProjectDirList);
        // 查询上级目录名
        if (!mapProjectDirList.isEmpty()) {
            mapProjectDirList.stream().forEach(dir->{
                MapProjectDir projectDir = mapProjectDirService.getById(dir.getParentId());
                dir.setParentName(projectDir != null? projectDir.getName(): null);
            });
        }
        return R.data(mapProjectDirList);
    }

    /**
    * @描述: 专题目录拖拽排序
    * @入参:
    * @出参:
    * @作者: 代鹏刚
    * @日期: 2020/2/19 16:13
    **/
    @PostMapping("/moveSort")
    @ApiOperation(value = "专题目录拖拽排序")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "当前拖拽ID", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "targetId", value = "目标位置ID", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "ahead", value = "是否拖拽到目标位置下方(true:是 false:否)", required = true, dataType = "boolean", paramType = "query"),
            @ApiImplicitParam(name = "orgId", value = "拖拽到的机构ID", required = true, dataType = "string", paramType = "query")
    })
    public R moveSort(String id , String targetId, Boolean ahead, String orgId){
        //获取目标数据
        MapProjectDir targetData = mapProjectDirService.getById(targetId);
        //获取所有跟目标同级的数据
        MapProjectDir moveData = mapProjectDirService.getById(id);
        String oldParentId = moveData.getParentId();
        Integer sort = moveData.getSort();
        List<MapProjectDir> mapProjectDirs = (List<MapProjectDir>)mapProjectDirService.listByMap(VerificationUtil.verifyMap("",moveData.getParentId()));
        if(ahead){
            //拖拽至目标下方的情况
            updateSort(moveData,targetData,orgId,true);
        }else {
            //拖拽至目标上方的情况
            updateSort(moveData,targetData,orgId,false);
        }
        //移动完成后，需要修改被移动数据同级的数据序号
        List<MapProjectDir> saveData = mapProjectDirs.stream().filter(s -> !s.getId().equals(id)).collect(Collectors.toList());
        if(saveData.size() > 0){
            if(!saveData.get(0).getParentId().equals(oldParentId)){
                for (MapProjectDir mapProjectDir:saveData) {
                    if(mapProjectDir.getSort() > sort){
                        mapProjectDir.setSort(mapProjectDir.getSort() - 1);
                    }
                }
                mapProjectDirService.updateBatchById(saveData);
            }
        }
        return R.data(null);
    }
    private void updateSort(MapProjectDir mp, MapProjectDir mapProjectDir, String orgId, Boolean isAhead){
        //1.查询当前拖拽到的目标父目录下所有的数据
        List<MapProjectDir> mapProjectDirList = (List<MapProjectDir>)mapProjectDirService.listByMap(VerificationUtil.verifyMap("",mapProjectDir.getParentId()));
        if(!isAhead){
            //2.拖拽至目标上方
            //同级拖拽
            if(mp.getParentId().equals(mapProjectDir.getParentId())){
                if(mp.getSort() > mapProjectDir.getSort()){
                    for (MapProjectDir mapProjectDir1:mapProjectDirList) {
                        if(mapProjectDir1.getSort() < mp.getSort() && mapProjectDir1.getSort() >= mapProjectDir.getSort()){
                            mapProjectDir1.setSort(mapProjectDir1.getSort() + 1);
                        }
                    }
                    //3.更新排序
                    mp.setSort(mapProjectDir.getSort());
                }else {
                    for (MapProjectDir mapProjectDir1:mapProjectDirList) {
                        if(mapProjectDir1.getSort() > mp.getSort() && mapProjectDir1.getSort() < mapProjectDir.getSort()){
                            mapProjectDir1.setSort(mapProjectDir1.getSort() - 1);
                        }
                    }
                    //3.更新排序
                    mp.setSort(mapProjectDir.getSort() - 1);
                }
            }else {
                for (MapProjectDir mapProjectDir1:mapProjectDirList) {
                    if(mapProjectDir1.getSort() >= mapProjectDir.getSort()){
                        mapProjectDir1.setSort(mapProjectDir1.getSort() + 1);
                    }
                }
                //3.更新排序
                mp.setSort(mapProjectDir.getSort());
            }
            mapProjectDirService.updateBatchById(mapProjectDirList);
        }else {
            //2.拖拽至目标下方
            //同级拖拽
            if(mp.getParentId().equals(mapProjectDir.getParentId())){
                if(mp.getSort() < mapProjectDir.getSort()){
                    for (MapProjectDir mapProjectDir1:mapProjectDirList) {
                        if(mapProjectDir1.getSort() > mp.getSort() && mapProjectDir1.getSort() <= mapProjectDir.getSort()){
                            mapProjectDir1.setSort(mapProjectDir1.getSort() - 1);
                        }
                    }
                    //3.更新排序
                    mp.setSort(mapProjectDir.getSort());
                }else {
                    for (MapProjectDir mapProjectDir1:mapProjectDirList) {
                        if(mapProjectDir1.getSort() < mp.getSort() && mapProjectDir1.getSort() > mapProjectDir.getSort()){
                            mapProjectDir1.setSort(mapProjectDir1.getSort() + 1);
                        }
                    }
                    //3.更新排序
                    mp.setSort(mapProjectDir.getSort() + 1);
                }
            }else {
                for (MapProjectDir mapProjectDir1:mapProjectDirList) {
                    if(mapProjectDir1.getSort() > mapProjectDir.getSort()){
                        mapProjectDir1.setSort(mapProjectDir1.getSort() + 1);
                    }
                }
                //3.更新排序
                mp.setSort(mapProjectDir.getSort() + 1);
            }
            mapProjectDirService.updateBatchById(mapProjectDirList);
        }
        //4.更新拖拽的数据
        mp.setOrgId(orgId);
        mp.setParentId(mapProjectDir.getParentId());
        mapProjectDirService.updateById(mp);
    }

    private boolean prepareData(MapProjectDir mapProjectDir, boolean isSave) {
        //判断同一级目录下，目录名称是否已经存在
        if(isSave){
            Map map = VerificationUtil.verifyMap(mapProjectDir.getName(),mapProjectDir.getParentId());
            map.put("project_id",mapProjectDir.getProjectId());
            List<MapProjectDir> list = (List<MapProjectDir>)mapProjectDirService.listByMap(map);
            if(list.size() > 0){
                return false;
            }
            mapProjectDir.setCreator(getUser().getUserId().toString());
            mapProjectDir.setCreateTime(new Date());
            //防止误修改
            mapProjectDir.setModifier(null);
            mapProjectDir.setModifyTime(null);
            return true;
        }else{
            Map map = new HashMap();
            if(mapProjectDir.getType() == 1){
                map = VerificationUtil.verifyMap(mapProjectDir.getName(),mapProjectDir.getParentId());
            }else {
                map = VerificationUtil.verifyMapByAlias(mapProjectDir.getAlias(),mapProjectDir.getParentId());
            }
            map.put("project_id",mapProjectDir.getProjectId());
            List<MapProjectDir> list = (List<MapProjectDir>)mapProjectDirService.listByMap(map);
            if(list.size() > 0 && !list.get(0).getId().equals(mapProjectDir.getId())){
                return false;
            }
            mapProjectDir.setModifier(getUser().getUserId().toString());
            mapProjectDir.setModifyTime(new Date());
            //防止误修改
            mapProjectDir.setCreator(null);
            mapProjectDir.setCreateTime(null);
            return true;
        }
    }

    /**
    * @描述:根据专题编码查询当前用户的专题授权专题目录树
    * @入参:
    * @出参:
    * @作者: 郑文彬
    * @日期: 2020/4/16 9:34
    **/
    @PostMapping("/listTreeByCodeAndParentId")
    @ApiOperation(value = " 根据专题编码和父节点id查询专题目录树")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "专题编码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "父id", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "isDir", value = "是否为目录层(true:是 false:否)", required = true, dataType = "boolean", paramType = "query"),
    })
    public R listTreeByCodeAndParentId(String code , String parentId, boolean isDir) {
        PageData pd = new PageData(this.getRequest());
        List<MapProjectDir> dataList = mapProjectDirService.listTreeByCodeAndParentId(code ,parentId,isDir);
        List tree = mapProjectDirService.createTree(pd.getString("parentId"), dataList);
        return R.data(tree);
    }

    /**
     * @描述:根据目录id查询目录下的所有图层
     * @入参:
     * @出参:
     * @作者: 郑文彬
     * @日期: 2020/4/16 9:34
     **/
    @PostMapping("/listLayerByDirId")
    @ApiOperation(value = " 根据目录id查询目录下的所有图层")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dirId", value = "目录id(当前点击的目录id)", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "专题编码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键字搜索",  dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页码", dataType = "long", paramType = "query", example = "1"),
            @ApiImplicitParam(name = "size", value = "每页显示数量", dataType = "long", paramType = "query", example = "10")
    })
    public R listLayerByDirId(String dirId, String code, String keyword, @ApiIgnore Page page) {
        IPage<MapLayer> iPage = mapProjectDirService.listLayerByDirId(page,dirId,code,keyword);
        List<MapLayer> list = new ArrayList<>(iPage.getRecords());
        //可能点的是图层
        MapProjectDir mapProjectDir = mapProjectDirService.getById(dirId);
        if(mapProjectDir!=null && mapProjectDir.getType()==2){
            MapLayer mapLayer = mapLayerService.getById(mapProjectDir.getLayerId());
            if(mapLayer!=null){
                list.add(mapLayer);
            }
            iPage.setTotal(list.size());
        }
        String str = "yyyy年MM月dd日";
        SimpleDateFormat sdf = new SimpleDateFormat(str);
        // 获取图层类型数据字典集合
        List<DictVO> tclxBizList = iDictBizClient.getList("TCLX").getData();
        for (MapLayer layer: list) {
            if(StringUtils.isNotBlank(layer.getLayerType())){
                //字典转化 --新基础运维
                for (DictVO biz : tclxBizList) {
                    if (layer.getLayerType().equals(biz.getDictKey())) {
                        layer.setRemark(biz.getDictValue());
                        break;
                    }
                }
            }
            if(layer.getCreateTime()!=null){
                layer.setDate(sdf.format(layer.getCreateTime()));
            }
        }
        iPage.setRecords(list);
        return R.data(iPage);
    }

    /**
     * @描述：收藏图层，只收藏图层和图层目录，如果是图层目录，则只收藏目录，但是查询时必须级联查询其下的子级图层
     * @作者: 陈宏成
     * @日期: 2021-03-30
     */
    @PostMapping("/collect")
    @ApiOperation(value = "收藏图层")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectDirId", value = "专题目录的图层id，也就是专题目录中图层类型的project_dir_id", required = true, dataType = "string", paramType = "query"),
    })
    @Transactional(rollbackFor = Exception.class)
    public R collect(String projectDirId){
        LoginUser user = this.getUser();

        if (!org.springframework.util.StringUtils.hasText(projectDirId)){
            return R.fail(StatusCode.ERROR_CODE_40005,"必须选择图层");
        }

        MapProjectDir projectDir = this.iMapProjectDirService.getById(projectDirId);
        if (projectDir == null){
            return R.fail(StatusCode.ERROR_CODE_40005,"图层不存在");
        }
        if (projectDir.getType() == 1 && projectDir.getIsLayerDir() != 1){
            return R.fail(StatusCode.ERROR_CODE_40005,"目录不能收藏");
        }
        MapLayerCollect mapLayerCollect = new MapLayerCollect();
        mapLayerCollect.setId(UuidUtil.get32UUID());
        mapLayerCollect.setProjectDirId(projectDirId);
        mapLayerCollect.setCreator(user.getUserId().toString());
        mapLayerCollect.setCreateTime(new Date());
        this.iMapLayerCollectService.save(mapLayerCollect);
        // 返回
        projectDir.setIsCollect(1);
        if (org.springframework.util.StringUtils.hasText(projectDir.getLayerId())){
            projectDir.setMapLayer(this.mapLayerService.getById(projectDir.getLayerId()));
        }
        if(projectDir.getIsLayerDir() == 1){
            // 图层目录，需要去找他的子目录
            List<String> roleIds = Func.toStrList(user.getRoleId());
            List<Map<String, Object>> layerDirMap = this.iMapLayerCollectService.listLayerDirMap(roleIds,projectDir.getId());
            projectDir.setLayerDirMap(layerDirMap);
        }
        return R.data(projectDir);
    }

    /**
     * @描述：取消收藏图层
     * @作者: 陈宏成
     * @日期: 2021-03-30
     */
    @PostMapping("/disCollect")
    @ApiOperation(value = "取消收藏图层")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectDirId", value = "专题目录的图层id，也就是专题目录中图层类型的project_dir_id", required = true, dataType = "string", paramType = "query"),
    })
    @Transactional(rollbackFor = Exception.class)
    public R disCollect(String projectDirId){
        LoginUser user = this.getUser();

        if (!org.springframework.util.StringUtils.hasText(projectDirId)){
            return R.fail(StatusCode.ERROR_CODE_40005,"必须选择图层");
        }

        LambdaQueryWrapper<MapLayerCollect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MapLayerCollect::getCreator,user.getUserId().toString());
        queryWrapper.eq(MapLayerCollect::getProjectDirId,projectDirId);
        this.iMapLayerCollectService.remove(queryWrapper);

        // 返回
        MapProjectDir projectDir = this.iMapProjectDirService.getById(projectDirId);
        if (projectDir == null){
            return R.data(null);
        }
        projectDir.setIsCollect(0);
        if (org.springframework.util.StringUtils.hasText(projectDir.getLayerId())){
            projectDir.setMapLayer(this.mapLayerService.getById(projectDir.getLayerId()));
        }
        if(projectDir.getIsLayerDir() == 1){
            // 图层目录，需要去找他的子目录
            List<String> roleIds = Func.toStrList(user.getRoleId());
            List<Map<String, Object>> layerDirMap = this.iMapLayerCollectService.listLayerDirMap(roleIds,projectDir.getId());
            projectDir.setLayerDirMap(layerDirMap);
        }
        return R.data(projectDir);
    }

    /**
     * @描述: 返回专题附件目录树，最外层为挂载附件的专题目录或专题图层节点
     * @入参:
     * @出参:
     * @作者: 陈宏成
     * @日期: 2021-04-28 09:48:00
     **/
    @PostMapping("/treeProjectDirFile")
    @ApiOperation(value = " 返回附件目录树")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectCode", value = "专题编码", required = true, dataType = "string", paramType = "query")
    })
    public R<List<MapProjectDir>> treeProjectDirFile(String projectCode){
        LoginUser user = this.getUser();
        // 查询树
        List<MapProjectDir> mapProjectDirList = this.iMapProjectDirService.listProjectDirHasFile(Arrays.asList(user.getRoleId().split(",")), projectCode);
        return R.data(mapProjectDirList);
    }

    /**
     * @描述: 获取专题目录/图层下关联的附件目录树
     * @入参:
     * @出参:
     * @作者: 陈宏成
     * @日期: 2021-04-28 09:48:00
     **/
    @PostMapping("/getProjectDirFile")
    @ApiOperation(value = "获取专题目录/图层下关联的附件目录树")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "projectDirId", value = "专题目录/图层id", required = true, dataType = "string", paramType = "query")
    })
    public R<MapProjectDir> getProjectDirFile(String projectDirId){
        // 查询专题目录/图层
        if (!StringUtils.isNotBlank(projectDirId)){
            return R.fail(StatusCode.ERROR_CODE_40005,"必须选择一个目录或者图层");
        }
        MapProjectDir projectDir = this.iMapProjectDirService.getById(projectDirId);
        // 查询他们关联的附件树
        List<MapProjectFile> mapProjectFiles = this.mapProjectFileService.listTreeByEntity(projectDir.getId());
        // 构建附件树
        List<MapProjectFile> treeFile = RecursionUtil.buildMapProjectFileTree(mapProjectFiles, projectDir.getId());
        projectDir.setProjectFiles(treeFile);
        return R.data(projectDir);
    }

}
